<?php
/* Include statements */
/* Include configuration variables */
include '../config.php';
/* Include classes needed to generate the assertion */
include '../classes/assertion_classes.php';
/* Include utility functions */
include 'utils.php';

session_start();

$location = 'Location: ' . $ISSUER_HOST . '/create_assertion_result.php';

// Connecting, selecting database
$mysqli = new mysqli($MYSQL_HOST, $MYSQL_USERNAME, $MYSQL_PASSWORD, $MYSQL_DB_NAME);
if ($mysqli->connect_errno) {
	$_SESSION[$CA_MSG_TAG] = $DB_CONN_ERR;
	$_SESSION[$DB_CONN_ERRNO] = $mysqli->connect_errno;
	$_SESSION[$DB_CONN_ERROR] = $mysqli->connect_error;
	header($location);
	exit();
}

$mysqli->set_charset("utf8");

// Get POST values
$array = preg_split('/#/', $_POST['user']);
$earnerId = $array[0];
$earnerEmail = $array[1];

$array = preg_split('/#/', $_POST['badge']);
$badgeId = $array[0];
$badgeName = str_replace(' ', '_', trim($array[1]));
$condivisa = $array[2];

$evdience = $_POST["evidenceUrl"];
$expires = $_POST["expires"];

// Set filenames
$fileNameBase = "badge_" . $earnerId . "_" . $badgeName;
$bakedPNGName = "baked_" . $fileNameBase . ".png";
$jsonFileName = $fileNameBase . ".json";

// Hash email
$salt = randomString($SALT_LENGTH);
$hash = hashEmailAddress($earnerEmail, $salt);

// Create the IdentityObject
$recipient = new IdentityObject();
$recipient->setIdentity($hash);
$recipient->setType("email");
$recipient->setHashed(true);
$recipient->setSalt($salt);

// Create the VerificationObject
$verify = new VerificationObject();
$verify->setType($_POST['type']);
$assertionURL = $JSON_ASSERTIONS_URL . "/" . $jsonFileName;
/* Set the verification URL as needed based on assertion type */
/* IMPORTANT! At the moment there is no support (in the code) for signed assertions */
$verify->setURL(!strcmp($_POST['type'], "hosted") ? $assertionURL : $PUBLIC_KEY_URL);

// Create the BadgeAssertion
$assertion = new BadgeAssertion();
/* Set the UID of the assertion to md5($earnerEmail . $badgeName).
 * Since a earner cannot receive a badge more than once, this choice
 * guarantees that the UID remains unique */
$assertion->setUID(md5($earnerEmail . $badgeName));
$assertion->setRecipient($recipient->getArray());
if ($condivisa)
	$assertion->setBadge($JSON_BADGES_URL . "/badge_" . $badgeName . "_" . $_SESSION['id_issuer'] . ".json");
else
	$assertion->setBadge($JSON_BADGES_URL . "/badge_" . $badgeName . ".json");
$assertion->setVerify($verify->getArray());
$assertion->setIssuedOn();
/* Atm this cannot be set before creating the assertion...seems wierd */
//$assertion->setImage($BAKED_PNG_URL . "/" . $baked_png_name);

/* If an evidence URL is provided, verify if it is reachable.
 * If not, the evidence field is not set, since it can compromise
 * the creation of the assertion */
if ($evidence) {
	if (verifyURL($evdience))
		$assertion->setEvidence($evidence);
	else
		$_SESSION[$CA_EVIDENCE_WARN] = $evidence;
}

/* Date -> Timestamp transformation */
if ($expires) {
	$timestamp = strtotime($expires);
	$assertion->setExpires($timestamp);
}
else
	$timestamp = 0;

// Create JSON data
$jsonData = json_encode($assertion->getArray());

// Create assertion file
$created = createFile($JSON_ASSERTIONS_PATH_FROM_PHP, $jsonFileName, $jsonData);

if (!$created) {
	unlink($JSON_ASSERTIONS_PATH_FROM_PHP . "/" . $jsonFileName);
	mysqli_free_result($result);
	$mysqli->close();
	$_SESSION[$CA_MSG_TAG] = $FILE_ERR;
	header($location);
	exit();
}

/* Verify if assertion is valid.
 * The baking service will return a PNG file if assertion is validated;
 * if not, it returns JSON formatted data to describe the error */
$httpResult = getHTTPResponseContentType($BAKER_WS_URL . $assertionURL);

if (isset($httpResult)) {
	if (!strcmp($httpResult, "image/png")) {
		// Create baked image
		$ch = curl_init($BAKER_WS_URL . $assertionURL);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);		
		$bakedPNG = fopen($BAKED_PATH_FROM_PHP . "/" . $bakedPNGName, w);
		curl_setopt($ch, CURLOPT_FILE, $bakedPNG);
		curl_exec($ch);
		fclose($bakedPNG);
		
		$badgeURL = $BAKED_PNG_URL . "/" . $bakedPNGName;
		
		$issuer = $_SESSION['id_issuer'];
		
		// Insert assertion data into DB
		$query = sprintf($INSERT_BAKED_BADGE, $assertion->getUID(), $earnerId, $badgeId, 
				$verify->getType(), $verify->getURL(), $assertion->getIssuedOn(), $badgeURL, 
				$assertion->getEvidence(), $timestamp, $issuer);
		
		$result = $mysqli->query($query);
		
		if (!$result) {
			unlink($JSON_ASSERTIONS_PATH_FROM_PHP . "/" . $jsonFileName);
			mysqli_free_result($result);
			$mysqli->close();
			$_SESSION[$CA_MSG_TAG] = $QUERY_ERR;
			$_SESSION[$QUERY_TAG] = $query;
			$_SESSION[$QUERY_ERRNO] = $mysqli->errno;
			$_SESSION[$QUERY_ERROR] = $mysqli->error;
			header($location);
			exit();
		}
		
		mysqli_free_result($result);
		$mysqli->close();
		
		// Send email to earnerS
		$sent = sendEarnedBadgeEmail($earnerEmail, $badgeURL, TRUE);
		
		if (!$sent) {
			$_SESSION[$CA_MSG_TAG] = $MAIL_ERR;
		} else {
			$_SESSION[$CA_MSG_TAG] = $MSG_OK;
		}	
		
		header($location);
		exit();
		
	} else if (!strcmp($httpResult, "application/json")) {
		
		$ch = curl_init($BAKER_WS_URL . $assertionURL);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);		
		$data = curl_exec($ch);
		unlink($JSON_ASSERTIONS_PATH_FROM_PHP . "/" . $jsonFileName);
		mysqli_free_result($result);
		$mysqli->close();
		$_SESSION[$CA_MSG_TAG] = $JSON_TAG;
		$_SESSION[$CA_JSON_MSG] = $data;
		header($location);
		exit();
	} else { 
		unlink($JSON_ASSERTIONS_PATH_FROM_PHP . "/" . $jsonFileName);
		mysqli_free_result($result);
		$mysqli->close();
		$_SESSION[$CA_MSG_TAG] = $UNEXPECTED_CONTENT_TYPE;
		header($location);
		exit();
	}
} else {
	unlink($JSON_ASSERTIONS_PATH_FROM_PHP . "/" . $jsonFileName);
	mysqli_free_result($result);
	$mysqli->close();
	$_SESSION[$CA_MSG_TAG] = $NO_CONTENT_TYPE;
	header($location);
	exit();
}

?>
